var Upload = require('../models/upload.model');
var mongoose = require('mongoose');
var multer=require('multer');
var path = require('path');

var fs=require("fs")

//设置参数
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './uploads');
    },
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now()+path.extname(file.originalname))
    }
  });
exports.upload=function(req,res,next){
    var upload=multer({
        storage:storage,
        fileFilter:function(req,file,callback){
          var ext=path.extname(file.originalname);
          if(ext!=='.png'&&ext!=='.jpg'&&ext!=='.gif'){
            return callback(res.end('文件类型不符合'));
          }
          callback(null,true);
        }
      }).single('avatar')
    upload(req,res,function(err){
        res.json(req.file);
    })
}


exports.find = (req,res,next)=>{
    var query = req.body.query || {};
    console.log(req.body.query);
    Upload.find(query,function(err,data){
        res.json(data);
   })
}



exports.create = (req,res,next)=>{     //参数顺序不能乱，request -> response -> next
    var upload = new Upload(req.body);          //获取数据，并且Upload模块的实例化
    upload.save().then(data=>res.json(data)); //  将数据转换成JSON格式 存入数据库
    console.log('save success');
}

//查找单个数据（编辑）
exports.get = function(req,res,next){  
    var id=req.params.id;   
    Upload.findById(id,function(err,result){
        
        res.json(result)
    })
}




exports.remove = (req,res,next)=>{
    var ids = req.params.id.split(',');
    var bstop = true;
    ids.forEach((v)=>{
        Upload.findByIdAndRemove(v,(err,doc)=>{
            if(err){
                bstop = false;
            }
        });
        Upload.findById(v,function(err,result){
            console.log(typeof `../uploads/${result.filename}`)
            fs.unlink(`./uploads/${result.filename}`, function(err) {
                if (err) {
                    return console.error(err);
                }
                console.log("文件删除成功！");
             });
        })
    });
    if(bstop){
        res.json({msg:'数据删除成功',status:200});
    }else{
        res.json({msg:'数据删除失败',status:500});
    }
}

exports.update = (req,res,next)=>{
    var id = req.params.id;
    Upload.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>res.json({msg:"数据修改成功",status:200}));
}

exports.list = (req,res,next)=>{
    var page = (req.body.page)?req.body.page:1;

    //需要转成整型
    var rows = parseInt((req.body.rows)?req.body.rows:3);
    var queryCondition = {};
    var name = null;
    if(req.body.name && req.body.name.trim().length > 0){
        name = req.body.name;
        queryCondition = {"name":new RegExp(name,'i')};
    }

    Upload.paginate(queryCondition,{page:page,limit:rows},(err,result)=>{
        //实现动态显示条数
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    })
}